layui.config({
    base: "../../js/"
}).extend({
    "utilObj": "utilObj"
});
layui.use(['form', 'utilObj', 'laydate', 'table', 'layer'], function () {
    var form = layui.form
    layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        laydate = layui.laydate,
        table = layui.table,
        utilObj = layui.utilObj;
    var updateStoreUrl = "cms/store/updateStore";
    var insertStoreUrl = "cms/store/saveStore";
    form.on("submit(addStore)", function (data) {

        var lat = $('#store-lat').val();
        var lon = $('#store-lon').val();
        if (lat == "") {
            layer.msg("请定位地址后选择地址");
            return false;
        }
        var canAppoint = $('.canAppoint').val();
        canAppoint = canAppoint == 1 ? true : false;
        var fromDate = $('.fromTime').val();
        var toDate = $('.toTime').val();
        var storeType = $('.storeType').val();
        if (storeType == 3) {
            if (fromDate == "") {
                layer.msg("请选择开始时间");
                return false;
            }
            if (toDate == "") {
                layer.msg("请选择结束时间");
                return false;
            }
        }

        var storeId = $('#store-id').val();
        var storeName = $('.storeName').val();
        var storeEnglishName = $('.storeEnglishName').val();

        var storeContact = $('.storeContact').val();
        var contactNumber = $('.contactNumber').val();
        var storePhone = $('.storePhone').val();
        var salesList = $("input:checkbox[name='sales']");
        var sales = "";
        for (var index in salesList) {
            if (salesList[index].checked) {
                sales += (Number(index) + 1) + ",";
            }
        }
        if (sales.length > 0) {
            sales = sales.substring(0, sales.length - 1);
        }
        var sundayStart = $('#sunday-start').val();
        var sundayEnd = $('#sunday-end').val();

        var mondayStart = $('#monday-start').val();
        var mondayEnd = $('#monday-end').val();

        var tuesdayStart = $('#tuesday-start').val();
        var tuesdayEnd = $('#tuesday-end').val();

        var wednesdayStart = $('#wednesday-start').val();
        var wedneddayEnd = $('#wednesday-end').val();

        var thursdayStart = $('#thursday-start').val();
        var thursdayEnd = $('#thursday-end').val();

        var fridayStart = $('#friday-start').val();
        var fridayEnd = $('#friday-end').val();

        var saturdayStart = $('#saturday-start').val();
        var saturdayEnd = $('#saturday-end').val();

        var businessTime = mondayStart + "-" + mondayEnd + "|" +
            tuesdayStart + "-" + tuesdayEnd + "|" +
            wednesdayStart + "-" + wedneddayEnd + "|" +
            thursdayStart + "-" + thursdayEnd + "|" +
            fridayStart + "-" + fridayEnd + "|" +
            saturdayStart + "-" + saturdayEnd + "|" +
            sundayStart + "-" + sundayEnd;

        var eventTitle = $('.event-title').val();
        var eventEnglishTitle = $('.event-englishtitle').val();
        var eventUrl = $('.event-url').val();

        var country = $("[name='country']").val();
        var city = $("[name='city']").val();

        var storeAddress = $('.storeAddress').val();
        var storeEnglishAddress = $('.storeEnglishAddress').val();

        var requestData = {
            userId: utilObj.getUser().userId,
            storeName: storeName,
            type: storeType,
            storeNameEn: storeEnglishName,
            contact: storeContact,
            contactNumber: contactNumber,
            storePhone: storePhone,
            saleList: sales,
            canAppoint: canAppoint,
            openTime: businessTime,
            eventTitle: eventTitle,
            eventTitleEn: eventEnglishTitle,
            eventURL: eventUrl,
            country: country,
            city: city,
            address: storeAddress,
            addressEn: storeEnglishAddress,
            lon: lon,
            lat: lat,
            startTime: fromDate,
            endTime: toDate
        };
        console.log(requestData);

        if (storeId) {
            requestData.storeId = storeId;
            storeEditPage.updateStoreInfo(requestData, updateStoreUrl);
        } else {
            storeEditPage.updateStoreInfo(requestData, insertStoreUrl);
        }
        console.log(requestData);
        return false;
    });

    var args = function (params) {
        var a = {};
        params = params || location.search;
        if (!params) return {};
        params = decodeURI(params);
        params.replace(/(?:^\?|&)([^=&]+)(?:\=)([^=&]+)(?=&|$)/g, function (m, k, v) {
            a[k] = v;
        });
        return a;
    };

    var storeEditPage = {
            getLocalAddredd: function (address) {
                if (address.length == 0) {
                    layer.msg("地址不能为空")
                } else {
                    storeEditPage.local.search(address);
                }
            },
            updateStoreInfo: function (requestData, requestUrl) {
                utilObj.showLoading();
                utilObj.ajax({
                    url: requestUrl,
                    type: "POST",
                    data: requestData,
                    success: function (data) {
                        console.log(data);
                        utilObj.hideLoading();
                        setTimeout(function () {
                            top.layer.msg("操作成功！");
                            layer.closeAll("iframe");
                            //刷新父页面
                            parent.location.reload();
                        }, 1000);
                    },
                    error: function (err) {
                        console.log(err);
                        utilObj.hideLoading();
                    }
                });
            },
            renderDateTime: function () {
                laydate.render({
                    elem: '#sunday-start'
                    , type: 'time'
                    , format: 'HH:mm'
                });
                laydate.render({
                    elem: '#sunday-end'
                    , type: 'time'
                    , format: 'HH:mm'
                });

                laydate.render({
                    elem: '#monday-start'
                    , type: 'time'
                    , format: 'HH:mm'
                });
                laydate.render({
                    elem: '#monday-end'
                    , type: 'time'
                    , format: 'HH:mm'
                });

                laydate.render({
                    elem: '#tuesday-start'
                    , type: 'time'
                    , format: 'HH:mm'
                });
                laydate.render({
                    elem: '#tuesday-end'
                    , type: 'time'
                    , format: 'HH:mm'
                });


                laydate.render({
                    elem: '#wednesday-start'
                    , type: 'time'
                    , format: 'HH:mm'
                });
                laydate.render({
                    elem: '#wednesday-end'
                    , type: 'time'
                    , format: 'HH:mm'
                });

                laydate.render({
                    elem: '#thursday-start'
                    , type: 'time'
                    , format: 'HH:mm'
                });
                laydate.render({
                    elem: '#thursday-end'
                    , type: 'time'
                    , format: 'HH:mm'
                });

                laydate.render({
                    elem: '#friday-start'
                    , type: 'time'
                    , format: 'HH:mm'
                });
                laydate.render({
                    elem: '#friday-end'
                    , type: 'time'
                    , format: 'HH:mm'
                });

                laydate.render({
                    elem: '#saturday-start'
                    , type: 'time'
                    , format: 'HH:mm'
                });
                laydate.render({
                    elem: '#saturday-end'
                    , type: 'time'
                    , format: 'HH:mm'
                });

                laydate.render({
                    elem: '.fromTime',
                    format: 'yyyy-MM-dd'
                });
                laydate.render({
                    elem: '.toTime',
                    format: 'yyyy-MM-dd'
                });
            },
            remakrPoint: function (point) {
                storeEditPage.map.centerAndZoom(point, 18);
                var marker = new BMap.Marker(point);
                storeEditPage.map.clearOverlays();
                storeEditPage.map.addOverlay(marker);
            },
            init: function () {
                storeEditPage.options = {
                    onSearchComplete: function (results) {
                        // 判断状态是否正确
                        if (storeEditPage.local.getStatus() == BMAP_STATUS_SUCCESS) {
                            storeEditPage.tableIns = table.render({
                                elem: '#address-list',
                                cellMinWidth: 95,
                                page: false,
                                height: 300,
                                cols: [[
                                    {
                                        field: 'title',
                                        title: '标题',
                                        align: "center",
                                        templet: function (d) {
                                            return d.title + "," + d.address
                                        }
                                    },
                                    {
                                        title: '操作',
                                        templet: '#addressListBar',
                                        fixed: "right",
                                        width: 100,
                                        align: "center"
                                    }
                                ]],
                                data: results.Br
                            });
                            var storeId = $('#store-id').val();
                            if (storeId == "") {
                                var firstLoc = results.Br[0];
                                if (firstLoc) {
                                    var point = new BMap.Point(firstLoc.point.lng, firstLoc.point.lat);
                                    storeEditPage.remakrPoint(point)
                                }
                            }
                        }
                    }
                }

                storeEditPage.map = new BMap.Map("allMap");
                storeEditPage.map.enableScrollWheelZoom(true);
                //初始化默认北京地图
                if (args().lat) {
                    var lat = args().lat;
                    var lon = args().lon;
                    $('#store-lat').val(lat);
                    $('#store-lon').val(lon);
                    var point = new BMap.Point(lon, lat);
                    storeEditPage.remakrPoint(point);
                } else {
                    var point = new BMap.Point(116.404, 39.915);
                    storeEditPage.map.centerAndZoom(point, 15);
                }

                storeEditPage.map.addEventListener("dblclick", function (e) {
                    var messageTitle = "是否设置这个点为店铺地址？"
                    var lng = e.point.lng;
                    var lat = e.point.lat;
                    layer.confirm(messageTitle, {
                        icon: 3,
                        title: '系统提示',
                        cancel: function (index) {
                            layer.close(index);
                        }
                    }, function (index) {
                        layer.close(index);
                        $("#store-lon").val(lng);
                        $("#store-lat").val(lat);
                        var point = new BMap.Point(lng, lat);
                        storeEditPage.remakrPoint(point)
                    }, function (index) {
                        layer.close(index);
                    });
                });
                storeEditPage.local = new BMap.LocalSearch(storeEditPage.map, storeEditPage.options);

                form.on('select(select-country)', function (data) {
                    storeEditPage.currentCountry = data.value;
                    $("[name='city']").html(`<option value="">请选择城市</option>`);
                    for (var obj in layer.cityList2) {
                        if (layer.cityList2[obj].id == data.value) {
                            var tempCity = layer.cityList2[obj].cityList;
                            for (var inIndex in tempCity) {
                                if (tempCity[inIndex].cityName)
                                    $("[name='city']").append(`<option value="${tempCity[inIndex].id}">
                                    ${tempCity[inIndex].cityName}</option>`);
                            }
                        }

                    }
                    form.render('select', "city");
                });

                form.on('select(select-storeType)', function (data) {
                    if (data.value == 3) {
                        $(".storeTime").show();
                        $(".fromTime").attr("lay-verify", "required");
                        $(".toTime").attr("lay-verify", "required");
                        // =""
                    } else {
                        $(".storeTime").hide();
                        $(".fromTime").removeAttr("lay-verify");
                        $(".toTime").removeAttr("lay-verify");
                    }
                });

                storeEditPage.renderDateTime();

                $(".locationAddress").on('click', function (event) {
                    var address = $(".storeAddress").val();
                    storeEditPage.getLocalAddredd(address)
                });

                table.on('tool(address-list)', function (obj) {
                        var layEvent = obj.event,
                            data = obj.data;
                        if (layEvent == "confirm") {
                            var point = new BMap.Point(data.point.lng, data.point.lat);
                            storeEditPage.map.centerAndZoom(point, 18);
                            var marker = new BMap.Marker(point);
                            storeEditPage.map.clearOverlays();
                            storeEditPage.map.addOverlay(marker);
                            $(".storeAddress").val(data.address);
                            $("#store-lon").val(data.point.lng);
                            $("#store-lat").val(data.point.lat);
                        }
                    }
                );
            }
        }
    ;
    storeEditPage.init();

    function setAddress(data) {
        alert(data);
    };
})
;